package org.lib.postgresqlhello;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;

import lombok.extern.slf4j.Slf4j;

/**
 * 测试接口
 * @author ben
 * @date 2021-11-20 14:49:02 CST
 */
@RestController
@RequestMapping(value="/test")
@Slf4j
public class TestController {

	@Autowired
	private DataSource ds;
	
	@Autowired
	private SqlSession sqls;
	
	@Autowired
	private SqlSessionFactory sqlsf;
	
	@Autowired
	private SqlSessionTemplate sqlst;
	
	@GetMapping(value="/ds")
	public Boolean testDs() {
		log.info("ds={}", ds);
		
		// 动态数据源
		if (ds instanceof DynamicRoutingDataSource) {
			DataSource dslib1 = ((DynamicRoutingDataSource) ds).getDataSource("lib1");
			log.info("dslib1={}, {}", dslib1.getClass(), dslib1);
			DataSource dslib2 = ((DynamicRoutingDataSource) ds).getDataSource("lib2");
			log.info("dslib2={}, {}", dslib2.getClass(), dslib2);
			
			// 不存在的
			DataSource dslib3 = ((DynamicRoutingDataSource) ds).getDataSource("lib3");
			log.info("dslib3={}, {}", dslib3.getClass(), dslib3);
		}
		
		try {
			log.info("ds={}", ds.getLoginTimeout());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		try (Connection conn = ds.getConnection()) {
			log.info("1 conn={}", conn);
			log.info("2 conn={}, {}, clientInfo={}, {}, schema={}", conn.getAutoCommit(), conn.getCatalog(), conn.getClientInfo(),
					conn.getNetworkTimeout(), conn.getSchema());
			log.info("3 conn={}", conn.getTypeMap());
			
			DatabaseMetaData dbmd = conn.getMetaData();
			log.info("1 dbmd={}", dbmd);
			log.info("2 dbmd={}, {}, {}, username={}, url={}", dbmd.getDatabaseProductName(),
					dbmd.getDatabaseMajorVersion(), dbmd.getDatabaseMinorVersion(),
					dbmd.getUserName(), dbmd.getURL());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return true;
	}
	
}
